package com.xbongbong.saas.service.toolbox.help;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.field.SubFormPoJo;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.pojo.vo.PrePaymentBalanceListVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CalendarUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.ItemUtil;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.weblist.pojo.SaasAnalysisDataFieldPojo;
import com.xbongbong.pro.workorder.pojo.vo.PaymentSheetDateEsListVO;
import com.xbongbong.pro.workorder.pojo.vo.WorkOrderDataEsListVO;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.PaymentBalanceEntity;
import com.xbongbong.saas.domain.entity.ext.PaymentSheetEntityExt;
import com.xbongbong.saas.domain.entity.ext.WorkOrderEntityExt;
import com.xbongbong.saas.enums.BirthdayTypeEnum;
import com.xbongbong.saas.enums.InstockTypeEnum;
import com.xbongbong.saas.enums.OutstockTypeEnum;
import com.xbongbong.saas.enums.PaymentLinkTypeEnum;
import com.xbongbong.saas.enums.PaymentSourceTypeEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.WorkOrderNodeStatusEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.InstockEnum;
import com.xbongbong.saas.enums.business.OutstockEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.toolbox.help.TimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author haibin.zhang
 * @version v1.0
 * @date 2019/5/20 9:31
 * @since v1.0
 */
@Component
public class AnalysisSaasDataListHelp {

    private static final Logger LOG = LoggerFactory.getLogger(AnalysisSaasDataListHelp.class);
    /**
     * 表单数据渲染
     * @param formDataEsListVO
     * @param explainMap
     * @throws XbbException
     */
    public void analysisSaasDataList(PaasFormDataEsListVO formDataEsListVO, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        List<PaasFormDataEntityExt> list = formDataEsListVO.getPaasFormDataESList();
        if (list == null || list.isEmpty()) {
            return;
        }
        SaasAnalysisDataFieldPojo saasAnalysisDataFieldPojo = packageDataField(explainMap, formDataEsListVO.getBusinessType());
        for (PaasFormDataEntityExt entity : list) {
            JSONObject data = entity.getData();
            if (data == null) {
                entity.setData(new JSONObject());
                continue;
            }
            analysisSaasData(data, saasAnalysisDataFieldPojo, explainMap);
        }
    }

    public void analysisSaasDataList(PrePaymentBalanceListVO prePaymentBalanceListVO, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        List<PaymentBalanceEntity> list = prePaymentBalanceListVO.getPaasFormDataESList();
        if (list == null || list.isEmpty()) {
            return;
        }
        SaasAnalysisDataFieldPojo saasAnalysisDataFieldPojo = packageDataField(explainMap, prePaymentBalanceListVO.getBusinessType());
        for (PaymentBalanceEntity entity : list) {
            JSONObject data = entity.getData();
            if (data == null) {
                entity.setData(new JSONObject());
                continue;
            }
            analysisSaasData(data, saasAnalysisDataFieldPojo, explainMap);
        }
    }

    /**
     * 工单字段渲染
     * @param workOrderDataEsListVO
     * @param explainMap
     * @throws XbbException
     */
    public void analysisSaasDataList(WorkOrderDataEsListVO workOrderDataEsListVO, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        List<WorkOrderEntityExt> list = workOrderDataEsListVO.getPaasFormDataESList();
        if (list == null || list.isEmpty()) {
            return;
        }
        SaasAnalysisDataFieldPojo saasAnalysisDataFieldPojo = packageDataField(explainMap,XbbRefTypeEnum.WORK_ORDER.getCode());
        for (WorkOrderEntityExt entity : list){
            JSONObject data = entity.getData();
            if (data == null) {
                entity.setData(new JSONObject());
                continue;
            }
            analysisSaasData(data,saasAnalysisDataFieldPojo,explainMap);
            if (Objects.equals(workOrderDataEsListVO.getPlatform(), PlatFormEnum.WEB.getValue())) {
                data.put(FieldTypeEnum.SERIALNO.getAlias(),entity.getSerialNo());
                data.put(FieldTypeEnum.CLOSETIME.getAlias(),entity.getCloseTime());
                data.put(FieldTypeEnum.ENDTIME.getAlias(),entity.getEndTime());
                data.put(FieldTypeEnum.WORK_ORDER_STATUS.getAlias(),WorkOrderNodeStatusEnum.getByCode(entity.getStatus()).getName());
            }
        }
    }

    /**
     * 工单字段渲染
     * @param workOrderDataEsListVO
     * @param explainMap
     * @throws XbbException
     */
    public void analysisSaasDataList4Web(WorkOrderDataEsListVO workOrderDataEsListVO, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        List<WorkOrderEntityExt> list = workOrderDataEsListVO.getPaasFormDataESList();
        if (list == null || list.isEmpty()) {
            return;
        }
        SaasAnalysisDataFieldPojo saasAnalysisDataFieldPojo = packageDataField4Web(explainMap,XbbRefTypeEnum.WORK_ORDER.getCode());
        for (WorkOrderEntityExt entity : list){
            JSONObject data = entity.getData();
            if (data == null) {
                entity.setData(new JSONObject());
                continue;
            }
            analysisSaasData4Web(data,saasAnalysisDataFieldPojo,explainMap);
            if (Objects.equals(workOrderDataEsListVO.getPlatform(), PlatFormEnum.WEB.getValue())) {
                data.put(FieldTypeEnum.SERIALNO.getAlias(),entity.getSerialNo());
                data.put(FieldTypeEnum.CLOSETIME.getAlias(),entity.getCloseTime());
                data.put(FieldTypeEnum.ENDTIME.getAlias(),entity.getEndTime());
                data.put(FieldTypeEnum.WORK_ORDER_STATUS.getAlias(),WorkOrderNodeStatusEnum.getByCode(entity.getStatus()).getName());
            }
        }
    }
    /**
     * Description: 工单全部列表字段渲染
     * @param workOrderDataEsListVO
     * @param formIdAndExplainMap
     * @return void
     * @author 魏荣杰
     * @date 2019/8/27 16:03
     * @since v4.3.0
     */
    public void analysisSaasDataAllList(WorkOrderDataEsListVO workOrderDataEsListVO, Map<Long, Map<String,FieldAttrEntity>> formIdAndExplainMap) throws XbbException {
        List<WorkOrderEntityExt> list = workOrderDataEsListVO.getPaasFormDataESList();
        if (list == null || list.isEmpty()) {
            return;
        }
        for (WorkOrderEntityExt entity : list) {
            Map<String, FieldAttrEntity> explainMap = formIdAndExplainMap.get(entity.getFormId());
            SaasAnalysisDataFieldPojo saasAnalysisDataFieldPojo = packageDataField(explainMap,XbbRefTypeEnum.WORK_ORDER.getCode());
            JSONObject data = entity.getData();
            if (data == null) {
                entity.setData(new JSONObject());
                continue;
            }
            analysisSaasData(data,saasAnalysisDataFieldPojo,explainMap);
            if (Objects.equals(workOrderDataEsListVO.getPlatform(), PlatFormEnum.WEB.getValue())) {
                data.put(FieldTypeEnum.SERIALNO.getAlias(),entity.getSerialNo());
                data.put(FieldTypeEnum.CLOSETIME.getAlias(),entity.getCloseTime());
                data.put(FieldTypeEnum.ENDTIME.getAlias(),entity.getEndTime());
                data.put(FieldTypeEnum.WORK_ORDER_STATUS.getAlias(),WorkOrderNodeStatusEnum.getByCode(entity.getStatus()).getName());
            }
        }
    }

    /**
     * Description: 工单全部列表字段渲染
     * @param workOrderDataEsListVO
     * @param formIdAndExplainMap
     * @return void
     * @author 魏荣杰
     * @date 2019/8/27 16:03
     * @since v4.3.0
     */
    public void analysisSaasDataAllList4Web(WorkOrderDataEsListVO workOrderDataEsListVO, Map<Long, Map<String,FieldAttrEntity>> formIdAndExplainMap) throws XbbException {
        List<WorkOrderEntityExt> list = workOrderDataEsListVO.getPaasFormDataESList();
        if (list == null || list.isEmpty()) {
            return;
        }
        for (WorkOrderEntityExt entity : list) {
            Map<String, FieldAttrEntity> explainMap = formIdAndExplainMap.get(entity.getFormId());
            SaasAnalysisDataFieldPojo saasAnalysisDataFieldPojo = packageDataField4Web(explainMap,XbbRefTypeEnum.WORK_ORDER.getCode());
            JSONObject data = entity.getData();
            if (data == null) {
                entity.setData(new JSONObject());
                continue;
            }
            analysisSaasData4Web(data,saasAnalysisDataFieldPojo,explainMap);
            if (Objects.equals(workOrderDataEsListVO.getPlatform(), PlatFormEnum.WEB.getValue())) {
                data.put(FieldTypeEnum.SERIALNO.getAlias(),entity.getSerialNo());
                data.put(FieldTypeEnum.CLOSETIME.getAlias(),entity.getCloseTime());
                data.put(FieldTypeEnum.ENDTIME.getAlias(),entity.getEndTime());
                data.put(FieldTypeEnum.WORK_ORDER_STATUS.getAlias(),WorkOrderNodeStatusEnum.getByCode(entity.getStatus()).getName());
            }
        }
    }

    public void analysisSaasDataList(PaymentSheetDateEsListVO paymentSheetDateEsListVO, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        List<PaymentSheetEntityExt> list = paymentSheetDateEsListVO.getPaasFormDataESList();
        if (list == null || list.isEmpty()) {
            return;
        }
        SaasAnalysisDataFieldPojo saasAnalysisDataFieldPojo = packageDataField(explainMap, XbbRefTypeEnum.PAYMENT_SHEET.getCode());
        for (PaymentSheetEntityExt entity : list) {
            JSONObject data = entity.getData();
            if (data == null) {
                entity.setData(new JSONObject());
                continue;
            }
            analysisSaasData(data, saasAnalysisDataFieldPojo, explainMap);
        }
    }

    /**
     * 封装字段
     * @param explainMap
     * @return
     * @throws XbbException
     */
    public SaasAnalysisDataFieldPojo packageDataField(Map<String, FieldAttrEntity> explainMap,Integer businessType) throws XbbException {
        SaasAnalysisDataFieldPojo saasAnalysisDataFieldPojo = new SaasAnalysisDataFieldPojo();
        for (Map.Entry<String, FieldAttrEntity> entry : explainMap.entrySet()) {
            FieldAttrEntity fieldAttrEntity = entry.getValue();
            Integer fieldType = fieldAttrEntity.getFieldType();
            //关联数据渲染
            if (Objects.equals(fieldType, FieldTypeEnum.LINK_BUSINESS_SINGLE.getType()) || Objects.equals(fieldType, FieldTypeEnum.LINK_BUSINESS_MULTI.getType()) /*|| Objects.equals(fieldType,FieldTypeEnum.LINK_RECEIVER.getType())*/) {
                String linkedText = Objects.isNull(fieldAttrEntity.getLinkedText()) ? "" : fieldAttrEntity.getLinkedText();
                saasAnalysisDataFieldPojo.getLinkBusinessMap().put(fieldAttrEntity.getAttr(), linkedText);
            }
            //下拉选项渲染
            if (Objects.equals(fieldType, FieldTypeEnum.COMBO.getType())
                    ||Objects.equals(fieldType, FieldTypeEnum.RADIO_GROUP.getType())
                    || Objects.equals(fieldType, FieldTypeEnum.CHECKBOX_GROUP.getType())
                    || Objects.equals(fieldType, FieldTypeEnum.COMBO_CHECK.getType())) {
                /*if (Objects.equals(fieldAttrEntity.getAttr(), InstockEnum.TYPE.getAttr()) && Objects.equals(businessType, XbbRefTypeEnum.INSTOCK.getCode())) {
                    fieldAttrEntity.getItems().add(new ItemPoJo(InstockTypeEnum.ASSEMBLE_INSTOCK.getName(), InstockTypeEnum.ASSEMBLE_INSTOCK.getCode() + ""));
                }
                if (Objects.equals(fieldAttrEntity.getAttr(), OutstockEnum.TYPE.getAttr()) && Objects.equals(businessType, XbbRefTypeEnum.OUTSTOCK.getCode())) {
                    fieldAttrEntity.getItems().add(new ItemPoJo(OutstockTypeEnum.ASSEMBLE_OUTSTOCK.getName(), OutstockTypeEnum.ASSEMBLE_OUTSTOCK.getCode() + ""));
                }
                if (Objects.equals(fieldAttrEntity.getAttr(), OutstockEnum.TYPE.getAttr()) && Objects.equals(businessType, XbbRefTypeEnum.PAY_SHEET.getCode())) {
                    fieldAttrEntity.getItems().add(new ItemPoJo(OutstockTypeEnum.ASSEMBLE_OUTSTOCK.getName(), OutstockTypeEnum.ASSEMBLE_OUTSTOCK.getCode() + ""));
                }*/
                Map<String, String> itemMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (ItemPoJo itemPoJo : fieldAttrEntity.getItems()) {
                    if (Objects.nonNull(itemPoJo.getValue())) {
                        itemMap.put(itemPoJo.getValue().toString(), itemPoJo.getText());
                    }
                }
                saasAnalysisDataFieldPojo.getCombMap().put(entry.getKey(), itemMap);
            }
            //生日渲染
            if (Objects.equals(fieldType, FieldTypeEnum.BIRTHDAY.getType())) {
                String linkedText = fieldAttrEntity.getLinkedText();
                saasAnalysisDataFieldPojo.getBirthdayMap().put(fieldAttrEntity.getAttr(), linkedText);
            }
            //星级渲染
            if (Objects.equals(fieldType, FieldTypeEnum.STAR.getType())) {
                saasAnalysisDataFieldPojo.getStarAttrList().add(fieldAttrEntity.getAttr());
            }
            //子表单渲染
            if (Objects.equals(fieldType, FieldTypeEnum.CONTACT_NUMBER.getType()) || Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.SUB_FORM.getType())) {
                SubFormPoJo subFormPoJo = fieldAttrEntity.getSubForm();
                if (subFormPoJo == null) {
                    continue;
                }
                List<? extends FieldAttrEntity> subFormItem = subFormPoJo.getItems();
                for (FieldAttrEntity json : subFormItem) {
                    Integer subFieldType = json.getFieldType();
                    if (Objects.equals(subFieldType, FieldTypeEnum.COMBO.getType())
                            ||Objects.equals(subFieldType, FieldTypeEnum.RADIO_GROUP.getType())
                            ||Objects.equals(subFieldType, FieldTypeEnum.COMBO_CHECK.getType())
                            || Objects.equals(subFieldType, FieldTypeEnum.CHECKBOX_GROUP.getType())) {
                        Map<String, String> itemMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        for (ItemPoJo itemJson : json.getItems()) {
                            itemMap.put(itemJson.getValue().toString(), itemJson.getText());
                        }
                        saasAnalysisDataFieldPojo.getCombMap().put(entry.getKey() + "." + json.getAttr(), itemMap);
                    }
                }
            }

        }
        return saasAnalysisDataFieldPojo;
    }

    /**
     * 渲染数据
     * @param data
     * @param saasAnalysisDataFieldPojo
     * @param explainMap
     * @throws XbbException
     */
    private void analysisSaasData(JSONObject data, SaasAnalysisDataFieldPojo saasAnalysisDataFieldPojo, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        for (Map.Entry<String, String> entry : saasAnalysisDataFieldPojo.getLinkBusinessMap().entrySet()) {
            Integer linkBusinessType = multiBusiness(data, explainMap.get(entry.getKey()));
            formatListBusiness4Show(data, entry.getKey(), entry.getValue(), explainMap.get(entry.getKey()).getFieldType(), linkBusinessType);
        }
        for (Map.Entry<String, Map<String, String>> entry : saasAnalysisDataFieldPojo.getCombMap().entrySet()) {
            //字段值
            String key = Objects.toString(entry.getKey());
            if (key.contains(StringConstant.POINT)) {
                //子表单
                try {
                    List<String> keyList = StringUtil.toStringList(key, "\\.");
                    if (keyList == null || keyList.isEmpty()) {
                        continue;
                    }
                    FieldAttrEntity fieldAttrEntity = explainMap.get(keyList.get(0));
                    Map<String, FieldAttrEntity> subExplainMap = ExplainUtil.getExplainMapByList(fieldAttrEntity.getSubForm().getItems());
                    JSONArray subForm = data.getJSONArray(keyList.get(0));
                    if (Objects.isNull(subForm)) {
                        continue;
                    }
                    for (Object obj : subForm) {
                        JSONObject json = (JSONObject) obj;
                        // 子表单中内字段
                        String subAttr = keyList.get(1);
                        FieldAttrEntity subField = subExplainMap.get(subAttr);
                        if (Objects.equals(subField.getFieldType(), FieldTypeEnum.COMBO.getType())
                                || Objects.equals(subField.getFieldType(), FieldTypeEnum.RADIO_GROUP.getType())) {
                            // 解析下拉框
                            json.put(subAttr, ItemUtil.analysisComboReturnStrWithColor(json, subField));
                        } else if (Objects.equals(subField.getFieldType(), FieldTypeEnum.COMBO_CHECK.getType())
                                || Objects.equals(subField.getFieldType(), FieldTypeEnum.CHECKBOX_GROUP.getType())) {
                            // 解析下拉复选
                            json.put(subAttr, ItemUtil.getCommonItem(subField, json));
                        }
                    }
                    data.put(keyList.get(0), subForm);
                } catch (Exception e) {
                    //出错不做任何处理
                    LOG.error("",e);
                }
            } else {
                    FieldAttrEntity fieldAttrEntity = explainMap.get(key);
                    //下拉选项还活着
                    if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.COMBO.getType())
                            || Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.RADIO_GROUP.getType())) {
                        // 解析下拉框
                        if (Objects.equals(fieldAttrEntity.getSaasAttr(), ProductEnum.UNIT.getSaasAttr())) {
                            data.put(ProductEnum.UNIT.getSaasAttr(), data.getString(fieldAttrEntity.getAttr()));
                        }
                        if (Objects.equals(fieldAttrEntity.getSaasAttr(), SelectProductEnum.UNIT.getSaasAttr()) || Objects.equals(fieldAttrEntity.getSaasAttr(), ProductEnum.UNIT.getSaasAttr())) {
                            // 关联产品/产品单位特殊处理下
                            data.put(entry.getKey(), ItemUtil.analysisComboReturnStr(data, fieldAttrEntity));
                        }else if (!(data.get(fieldAttrEntity.getAttr()) instanceof ItemPoJo)){
                            data.put(entry.getKey(), ItemUtil.analysisComboReturnStrWithColor(data, fieldAttrEntity));
                        }
                    } else if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.COMBO_CHECK.getType())
                            || Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.CHECKBOX_GROUP.getType())) {
                        if (data.get(entry.getKey()) instanceof ArrayList || data.get(entry.getKey()) instanceof JSONArray) {

                            data.put(entry.getKey(), ItemUtil.getCommonItem(fieldAttrEntity, data));
                        } else {
                            // 为了访客计划的兼容
                            data.put(entry.getKey(), data.getString(entry.getKey()));
                        }

                    }

            }
        }
        for (Map.Entry<String, String> entry : saasAnalysisDataFieldPojo.getBirthdayMap().entrySet()) {
            formatBirthday4Show(data, entry.getKey(), entry.getValue());
        }
        for (String starAttr : saasAnalysisDataFieldPojo.getStarAttrList()) {
            Integer starValue;
            try {
                starValue = data.getInteger(starAttr);
            } catch (Exception e) {
                starValue = 0;
            }
            data.put(starAttr, starValue);
        }
        String stageAttr = saasAnalysisDataFieldPojo.getStageAttr();
        if (!stageAttr.isEmpty()) {
            data.put(stageAttr, saasAnalysisDataFieldPojo.getStageMap().getOrDefault(data.getString(stageAttr), I18nMessageUtil.getMessage(StringConstant.VALUE_NOT_SET)));
        }
        String wastageAttr = saasAnalysisDataFieldPojo.getWastageAttr();
        if (!wastageAttr.isEmpty()) {
            data.put(wastageAttr, saasAnalysisDataFieldPojo.getWastageMap().getOrDefault(data.getString(wastageAttr), I18nMessageUtil.getMessage(StringConstant.VALUE_NOT_SET)));
        }
        for (String attr : saasAnalysisDataFieldPojo.getLastConnectTimeList()){
            data.put(attr,TimeUtil.analysisLastConnectTime(data.getLong(attr)));
        }
    }

    /***
     * 关联业务是否有多种
     * fieldType 20001
     * @param data 数据
     * @param fieldAttrEntity 字段解释
     * @return
     */
    private Integer multiBusiness(JSONObject data, FieldAttrEntity fieldAttrEntity) {
        if (Objects.equals(fieldAttrEntity.getIsMultiBusiness(), 1)) {
            Integer parentBuisnessType = fieldAttrEntity.getBusinessType();
            if (Objects.equals(parentBuisnessType, XbbRefTypeEnum.INSTOCK.getCode())) {
                return InstockTypeEnum.getByCode(data.getInteger(InstockEnum.TYPE.getAttr())).getBusinessType();
            } else if (Objects.equals(parentBuisnessType, XbbRefTypeEnum.OUTSTOCK.getCode())) {
                return OutstockTypeEnum.getByCode(data.getInteger(OutstockEnum.TYPE.getAttr())).getBusinessType();
            } else if (Objects.equals(parentBuisnessType, XbbRefTypeEnum.PAYMENT.getCode())) {
                if (Objects.equals(PaymentEnum.CONTRACT.getAttr(), fieldAttrEntity.getAttr())) {
                    return PaymentLinkTypeEnum.getByCode(data.getInteger(PaymentEnum.REF_TYPE.getAttr())).getCode();
                } else if (Objects.equals(PaymentEnum.SOURCE_REF_TYPE.getAttr(), fieldAttrEntity.getAttr())) {
                    return PaymentSourceTypeEnum.getByBusinessType(data.getInteger(PaymentEnum.SOURCE_REF_TYPE.getAttr())).getBusinessType();
                }else if (Objects.equals(PaymentEnum.SOURCE.getAttr(), fieldAttrEntity.getAttr())) {
                    return PaymentSourceTypeEnum.getByBusinessType(data.getInteger(PaymentEnum.SOURCE_REF_TYPE.getAttr())).getBusinessType();
                }
            }
        } else {
            return fieldAttrEntity.getLinkedType();
        }
        return fieldAttrEntity.getLinkedType();
    }

    /**
     * 将数据库中的生日三个字段转换成json对象格式给前端显示
     *
     * @param result     前端传回的data数据
     * @param attr       要格式化的字段attr
     * @param birthdayFlag 阴历和公历的标识
     * @author chaoxiong.lei
     * @date 15:38 2019/1/21
     * @since v1.0
     **/
    public void formatBirthday4Show(JSONObject result, String attr, String birthdayFlag) throws XbbException {
        if (result == null || attr == null || birthdayFlag == null) {
//            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028);
            return;
        }
        try {
            // 获取生日是公历还是阴历
            Integer flag = result.getInteger(birthdayFlag);
            String birthday = result.getString(attr);
            if (!DateTimeUtil.isSDFDate(birthday)) {
                return;
            }
            JSONObject jsonObject = new JSONObject();
            if (Objects.equals(flag, BirthdayTypeEnum.LUNAR_BIRTHDAY.getValue())) {
                // 阴历生日
                jsonObject.put(StringConstant.BIRTHDAY_FLAG, flag);
                jsonObject.put(StringConstant.BIRTHDAY, birthday);
                jsonObject.put(StringConstant.VALUE, CalendarUtil.lunar2Str(birthday));
            } else if (Objects.equals(flag, BirthdayTypeEnum.BIRTHDAY.getValue())) {
                // 公历生日
                jsonObject.put(StringConstant.BIRTHDAY_FLAG, flag);
                jsonObject.put(StringConstant.BIRTHDAY, birthday);
                jsonObject.put(StringConstant.VALUE, birthday);
            }
            result.put(attr, jsonObject);
        } catch (Exception e) {
            // 类型转换异常
//            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
        }
    }

    /**
     * 拼装系统关联字段
     * @param result
     * @param attr
     * @param linkedAttr
     * @param fieldType
     * @param linkBusinessType
     * @throws XbbException
     */
    public void formatListBusiness4Show(JSONObject result, String attr, String linkedAttr, Integer fieldType,Integer linkBusinessType) throws XbbException {
        JSONArray jsonArray = new JSONArray();
        try {
            // 上层发现重复调用，避免出现抛错，加此逻辑
            if (result.get(attr) instanceof List) {
                if (CollectionsUtil.isEmpty(result.getJSONArray(attr))) {
                    return;
                }
                JSONArray list = result.getJSONArray(attr);
                for (Object object : list) {
                    if (object instanceof Map) {
                        return;
                    }
                }
            }
            // 获取关联业务的id
            String businessIdStr = result.getString(attr);
            // 获取关联业务的名称
            String businessNameStr = result.getString(linkedAttr);
            if (StringUtil.isNotEmpty(businessIdStr) && StringUtil.isEmpty(businessNameStr)){
                return;
            }
            if (StringUtil.isNotEmpty(businessIdStr)) {
                // 关联业务不是必填，所以可能没有值
                List<String> businessIdList = new ArrayList<>();
                List<String> businessNameList = new ArrayList<>();
                if (Objects.equals(FieldTypeEnum.LINK_BUSINESS_MULTI.getType(), fieldType)) {
                    // 鲁江：下拉多选不要用逗号或者竖线分割，存成array
                    businessIdStr = JSONObject.toJSONString(result.get(attr));
                    businessNameStr = JSONObject.toJSONString(result.get(linkedAttr));
                    businessIdList = JSON.parseArray(businessIdStr, String.class);
                    businessNameList = JSON.parseArray(businessNameStr, String.class);
                } else {
                    businessIdList = Arrays.asList(businessIdStr);
                    if (StringUtil.isNotEmpty(businessNameStr)) {
                        businessNameList = Arrays.asList(businessNameStr);
                    }
                }
                for (int i = 0; i < businessIdList.size(); i++) {
                    String businessIds = businessIdList.get(i);
                    if (StringUtil.isEmpty(businessIds) || Objects.equals("null", businessIds)){
                        continue;
                    }
                    Long businessId = Long.valueOf(businessIds);
                    String businessName = "";
                    if (CollectionsUtil.isNotEmpty(businessNameList) && i < businessNameList.size()) {
                        businessName = businessNameList.get(i);
                    }
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_ID, businessId);
                    jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_NAME, businessName);
                    jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_LINK_TYPE,linkBusinessType);
                    jsonObject.put("saasMark", SaasMarkEnum.SAAS.getCode());
                    jsonArray.add(jsonObject);
                }
                result.put(attr, jsonArray);
                result.put(linkedAttr, null);
            }
        } catch (Exception e) {
            LOG.error("businessId analysis error:" + attr + ",data:" + JSONObject.toJSONString(result),e);
            // 类型转换异常或数组下标越界
//            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
        }
    }

    public void analysisSaasDataList4Web(PaasFormDataEsListVO formDataEsListVO, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        List<PaasFormDataEntityExt> list = formDataEsListVO.getPaasFormDataESList();
        if (list == null || list.isEmpty()) {
            return;
        }
        SaasAnalysisDataFieldPojo saasAnalysisDataFieldPojo = packageDataField4Web(explainMap, formDataEsListVO.getBusinessType());
        for (PaasFormDataEntityExt entity : list) {
            JSONObject data = entity.getData();
            if (data == null) {
                entity.setData(new JSONObject());
                continue;
            }
            analysisSaasData4Web(data, saasAnalysisDataFieldPojo, explainMap);
        }
    }

    public void analysisSaasData4Web(JSONObject data, SaasAnalysisDataFieldPojo saasAnalysisDataFieldPojo, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        for (Map.Entry<String, String> entry : saasAnalysisDataFieldPojo.getLinkBusinessMap().entrySet()) {
            // 收货人特殊处理
            if (Objects.equals(explainMap.get(entry.getKey()).getFieldType(), FieldTypeEnum.LINK_RECEIVER.getType())) {
                data.put(entry.getKey(), data.get(entry.getValue()));
            }else {
                Integer linkBusinessType = multiBusiness(data, explainMap.get(entry.getKey()));
                formatListBusiness4Show(data, entry.getKey(), entry.getValue(), explainMap.get(entry.getKey()).getFieldType(), linkBusinessType);
            }
        }
        for (Map.Entry<String, String> entry : saasAnalysisDataFieldPojo.getBirthdayMap().entrySet()) {
            formatBirthday4Show(data, entry.getKey(), entry.getValue());
        }
    }

    public SaasAnalysisDataFieldPojo packageDataField4Web(Map<String, FieldAttrEntity> explainMap, Integer businessType) {
        SaasAnalysisDataFieldPojo saasAnalysisDataFieldPojo = new SaasAnalysisDataFieldPojo();
        for (Map.Entry<String, FieldAttrEntity> entry : explainMap.entrySet()) {
            FieldAttrEntity fieldAttrEntity = entry.getValue();
            Integer fieldType = fieldAttrEntity.getFieldType();
            //关联数据渲染
            if (Objects.equals(fieldType, FieldTypeEnum.LINK_BUSINESS_SINGLE.getType()) || Objects.equals(fieldType, FieldTypeEnum.LINK_BUSINESS_MULTI.getType())
                    || Objects.equals(fieldType, FieldTypeEnum.LINK_RECEIVER.getType())) {
                String linkedText = Objects.isNull(fieldAttrEntity.getLinkedText()) ? "" : fieldAttrEntity.getLinkedText();
                saasAnalysisDataFieldPojo.getLinkBusinessMap().put(fieldAttrEntity.getAttr(), linkedText);
            }
            //生日渲染
            if (Objects.equals(fieldType, FieldTypeEnum.BIRTHDAY.getType())) {
                String linkedText = fieldAttrEntity.getLinkedText();
                saasAnalysisDataFieldPojo.getBirthdayMap().put(fieldAttrEntity.getAttr(), linkedText);
            }
            //星级渲染
//            if (Objects.equals(fieldType, FieldTypeEnum.STAR.getType())) {
//                saasAnalysisDataFieldPojo.getStarAttrList().add(fieldAttrEntity.getAttr());
//            }
        }
        return saasAnalysisDataFieldPojo;
    }
}
